package light;

import math.Vecmath;
import ray.Ray;

public class LSphere extends Light
{
    
    private double radius;
    public void setRadius(double rad) { this.radius = rad; }
    
    public LSphere()
    {
        super();
        this.radius = 1.0f;
    }
    
    public double getIntersectT(Ray ray)
    {
        double a = Vecmath.dotProd(ray.getDirection(), ray.getDirection());
        double b = 2.0 * (Vecmath.dotProd(
            ray.getDirection(), 
            Vecmath.subtract(ray.getOrigin(), this.origin)
        ));
        double c = (
            Vecmath.dotProd(ray.getOrigin(), ray.getOrigin())
            + Vecmath.dotProd(this.origin, this.origin)
            - (2.0 * Vecmath.dotProd(ray.getOrigin(), this.origin))
            - (this.radius * this.radius)
        );
        double disc = b * b - 4.0 * a * c;
        
        if (disc < 0.0)
        {
            return Double.MAX_VALUE;
        }
        else
        {
            double sqrt = Math.sqrt(disc);
            double rec_2a = 1.0 / (2.0 * a);
            double t0 = -1.0 * (b + sqrt) * rec_2a;
            double t1 = -1.0 * (b - sqrt) * rec_2a;
            return Math.min(t0, t1);
        }
    }
    
    public double[] getDirection(
            double s0, 
            double s1)
    {
        double t0 = 2.0 * s0 - 1.0;
        double sqT0 = t0 * t0;
        double t1 = Math.PI * 2.0 * s1;
        double sqrt1mSqT0 = Math.sqrt(1.0 - sqT0);
        double x = sqrt1mSqT0 * Math.cos(t1);
        double y = sqrt1mSqT0 * Math.sin(t1);
        double z = t0;
        double[] dir = new double[] { x, y, z };
        return dir;
    }
    
}
